package com.example.other.netty.imdemo;

import com.example.other.netty.endecode.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Field;

public class IMServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodec.decode(byteBuf);

        if(packet instanceof LoginRequestPacket){
            Field userName = packet.getClass().getDeclaredField("userName");
            userName.setAccessible(true);

            Field password = packet.getClass().getDeclaredField("password");
            password.setAccessible(true);

            String name = (String) userName.get(packet);
            String pw = (String) password.get(packet);

            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            if(name.equals("GGGGj") && pw.equals("jjjjG")){
                loginResponsePacket.setResult("登录成功！");
                loginResponsePacket.setFlag(1);
            }else{
                loginResponsePacket.setResult("登录失败！");
                loginResponsePacket.setFlag(0);
            }
            ctx.writeAndFlush(PacketCodec.encode(loginResponsePacket));
        }else if(packet instanceof MessageRequestPacket){
            MessageRequestPacket messageRequestPacket = (MessageRequestPacket) packet;
            System.out.println("客户端发来消息：" + messageRequestPacket.getMessage());

            MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
            messageResponsePacket.setMessage("我收到了消息:" + messageRequestPacket.getMessage());
            ctx.writeAndFlush(PacketCodec.encode(messageResponsePacket));
        }
    }
}
